﻿using Engine;
using Engine.Animations;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using XNAnimation.Controllers;

namespace EngineDrawer.Animations
{
    public class AnimationDrawer : DrawableGameComponent
    {        
        readonly private Animation _animation;
        private AnimationController _animationController;
        private World _world;

        public AnimationDrawer(Animation animation,Game game)
            : base(game)
        {
            _animation = animation;
        }
        protected override void LoadContent()
        {
            _world = Game.Services.GetService(typeof (World)) as World;            
            _animationController = new AnimationController(_animation.SkinnedModel.SkeletonBones);
            _animationController.Speed = 0.4f;
            _animation.Scale = new Vector3(0.4f);            

            Texture2D axe = Game.Content.Load<Texture2D>("Textures\\axe");
            Texture2D dwarf = Game.Content.Load<Texture2D>("Textures\\dwarf");

            foreach (ModelMesh mesh in _animation.SkinnedModel.Model.Meshes)
            {
                foreach (SkinnedEffect effect in mesh.Effects)
                {
                    effect.Texture = dwarf;

                    if (mesh.Name == "axe")
                    {
                        effect.Texture = axe;
                    }

                    effect.EnableDefaultLighting();

                    effect.SpecularColor = new Vector3(0.25f);
                    effect.SpecularPower = 16;
                }
            }
            base.LoadContent();
        }

        public override void Update(GameTime time)
        {
            if (_animationController.AnimationClip == null ||
                _animationController.AnimationClip.Name != _animation.CurrentClip)
                _animationController.StartClip(_animation.SkinnedModel.AnimationClips[_animation.CurrentClip]);

            _animation.Update(time);
            _animationController.Update(time.ElapsedGameTime, _animation.WorldMatrix);
        }
        public override void Draw(GameTime gameTime)
        {
            GraphicsDevice.BlendState = BlendState.Opaque;
            GraphicsDevice.RasterizerState = RasterizerState.CullCounterClockwise;
            GraphicsDevice.DepthStencilState = DepthStencilState.Default;

            foreach (ModelMesh mesh in _animation.SkinnedModel.Model.Meshes)
            {
                foreach (SkinnedEffect effect in mesh.Effects)
                {
                    effect.SetBoneTransforms(_animationController.SkinnedBoneTransforms);
                    effect.World = Matrix.Identity;

                    effect.View = _world.ViewMatrix;
                    effect.Projection = _world.ProjMatrix;
                }

                mesh.Draw();
            }
        }
    }
}
